//
//  DudelViewController.m
//  Dudel
//   svn test
//  Created by JN on 2/23/10.
//  Copyright Apple Inc 2010. All rights reserved.
//

#import "DudelViewController.h"

#import "DudelView.h"

#import "PencilTool.h"
#import "LineTool.h"
#import "RectangleTool.h"
#import "EllipseTool.h"
#import "FreehandTool.h"
#import "TextTool.h"
#import "FontListController.h"
#import "FontSizeController.h"

@implementation DudelViewController

@synthesize currentTool, fillColor, strokeColor, strokeWidth, font, currentPopover;

- (void)deselectAllToolButtons {
	[textButton setImage:[UIImage imageNamed:@"button_text.png"]];
	[freehandButton setImage:[UIImage imageNamed:@"button_bezier.png"]];
	[ellipseButton setImage:[UIImage imageNamed:@"button_ellipse.png"]];
	[rectangleButton setImage:[UIImage imageNamed:@"button_rectangle.png"]];
	[lineButton setImage:[UIImage imageNamed:@"button_line.png"]];
	[pencilButton setImage:[UIImage imageNamed:@"button_cdots.png"]];
}

- (void)setCurrentTool:(id <Tool>)t {
  [currentTool deactivate];
  if (t != currentTool) {
    [currentTool release];
    currentTool = [t retain];
    currentTool.delegate = self;
    [self deselectAllToolButtons];
  }
  [currentTool activate];
  [dudelView setNeedsDisplay];
}

- (IBAction)touchTextItem:(id)sender {
  self.currentTool = [TextTool sharedTextTool];
	[textButton setImage:[UIImage imageNamed:@"button_text_selected.png"]];
}

- (IBAction)touchFreehandItem:(id)sender {
  self.currentTool = [FreehandTool sharedFreehandTool];
	[freehandButton setImage:[UIImage imageNamed:@"button_bezier_selected.png"]];
}

- (IBAction)touchEllipseItem:(id)sender {
  self.currentTool = [EllipseTool sharedEllipseTool];
	[ellipseButton setImage:[UIImage imageNamed:@"button_ellipse_selected.png"]];
}
- (IBAction)touchRectangleItem:(id)sender {
  self.currentTool = [RectangleTool sharedRectangleTool];
	[rectangleButton setImage:[UIImage imageNamed:@"button_rectangle_selected.png"]];
}
- (IBAction)touchLineItem:(id)sender {
  self.currentTool = [LineTool sharedLineTool];
	[lineButton setImage:[UIImage imageNamed:@"button_line_selected.png"]];
}
- (IBAction)touchPencilItem:(id)sender {
  self.currentTool = [PencilTool sharedPencilTool];
	[pencilButton setImage:[UIImage imageNamed:@"button_cdots_selected.png"]];
}

- (IBAction)touchSendPdfEmailItem:(id)sender {
  // set up PDF rendering context
  NSMutableData *pdfData = [NSMutableData data];
  UIGraphicsBeginPDFContextToData(pdfData, dudelView.bounds, nil);
  UIGraphicsBeginPDFPage();
  
  // tell our view to draw
  [dudelView drawRect:dudelView.bounds];
  
  // remove PDF rendering context
  UIGraphicsEndPDFContext();
  
  // send PDF data in mail message
  MFMailComposeViewController *mailComposer = [[[MFMailComposeViewController alloc] init] autorelease];
  mailComposer.mailComposeDelegate = self;
  [mailComposer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:@"Dudel creation.pdf"];
  [self presentModalViewController:mailComposer animated:YES];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  [currentTool touchesBegan:touches withEvent:event];
  [dudelView setNeedsDisplay];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
  [currentTool touchesCancelled:touches withEvent:event];
  [dudelView setNeedsDisplay];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  [currentTool touchesEnded:touches withEvent:event];
  [dudelView setNeedsDisplay];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  [currentTool touchesMoved:touches withEvent:event];
  [dudelView setNeedsDisplay];
}

#pragma mark MFMailComposeViewControllerDelegate

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
  [self dismissModalViewControllerAnimated:YES];
}

#pragma mark ToolDelegate

- (void)addDrawable:(id <Drawable>)d {
  [dudelView.drawables addObject:d];
  [dudelView setNeedsDisplay];
}

- (UIView *)viewForUseWithTool:(id <Tool>)t {
  return dudelView;
}

#pragma mark DudelViewDelegate
- (void)drawTemporary {
  [self.currentTool drawTemporary];
}

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
  [super viewDidLoad];
  self.currentTool = [PencilTool sharedPencilTool];
	[pencilButton setImage:[UIImage imageNamed:@"button_cdots_selected.png"]];
  self.fillColor = [UIColor lightGrayColor];
  self.strokeColor = [UIColor blackColor];
  self.strokeWidth = 2.0;
  self.font = [UIFont systemFontOfSize:24.0];
}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	self.currentPopover = nil;
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [self.currentPopover dismissPopoverAnimated:NO];
    self.currentPopover = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
  self.currentPopover = nil;
  self.currentTool = nil;
  self.fillColor = nil;
  self.strokeColor = nil;
    self.currentPopover = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
  [super dealloc];
}


//浮动界面消失，委托方法中调用自己的清理方法
- (void)handleDismissedPopoverController:(UIPopoverController*)popoverController
{
    if ([popoverController.contentViewController isMemberOfClass:[FontListController class]]) {
        // this is the font list, grab the new selection
        FontListController *flc = (FontListController *)popoverController.contentViewController;
        self.font = [UIFont fontWithName:flc.selectedFontName size:self.font.pointSize];
    } else if([popoverController.contentViewController isMemberOfClass:[FontSizeController class]]) {
        FontSizeController *fsc = (FontSizeController *)popoverController.contentViewController;
        self.font = fsc.font;
    }
    self.currentPopover = nil;
}


- (void)setupNewPopoverControllerForViewController:(UIViewController *)vc {
    if (self.currentPopover) {
        [self.currentPopover dismissPopoverAnimated:YES];
        [self handleDismissedPopoverController:self.currentPopover];
    }
    self.currentPopover = [[[UIPopoverController alloc] initWithContentViewController:vc] autorelease];
    self.currentPopover.delegate = self;
}

/*
 弹出控制器的内容由另外的视图控制器提供，在初始化弹出控制器时，需要为它提供另一个视图控制器，方法是initWithContentViewController。
 弹出控制器的呈现有两种方法，分别是presentPopoverFromRect:inView:permittedArrowDirections:animated和presentPopover FromBarButtonItem:permittedArrowDirections:animated。
 前者由一个矩形区域弹出，后者由一个按钮弹出。让弹出控制器消失可以使用方法dismissPopoverAnimated:。
 */
/*
 弹出控制器有两个代理方法。popoverControllerShouldDismissPopover:在用户取消弹出视图时被触发；popoverControllerDidDismissPopover:在弹出视图因用户行为被取消后被触发（注意，如果不是因用户行为被触发，而是因为调用了dismissPopoverAnimated:方法，那么这个代理方法不会被触发）
 */

- (IBAction)popoverFontName:(id)sender
{
    FontListController *flc = [[[FontListController alloc] initWithStyle:UITableViewStylePlain] autorelease];
    flc.selectedFontName = self.font.fontName;
    [self setupNewPopoverControllerForViewController:flc];
    flc.container = self.currentPopover;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fontListControllerDidSelect:) name:FontListControllerDidSelect object:flc];
    [self.currentPopover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (IBAction)popoverFontSize:(id)sender
{
    FontSizeController *fsc = [[[FontSizeController alloc] initWithNibName:nil bundle:nil] autorelease];
    fsc.font = self.font;
    [self setupNewPopoverControllerForViewController:fsc];
    self.currentPopover.popoverContentSize = fsc.view.frame.size;
    [self.currentPopover presentPopoverFromBarButtonItem:sender
                                permittedArrowDirections:UIPopoverArrowDirectionAny
                                                animated:YES];
}

- (IBAction)popoverStrokeColor:(id)sender
{
    
}

- (IBAction)popoverStrokeWidth:(id)sender
{
    
}

- (IBAction)popoverFillColor:(id)sender
{
    
}

/*
     // Implement loadView to create a view hierarchy programmatically, without using a nib.
     - (void)loadView {
     }
*/
#pragma popover callbacks
- (void)fontListControllerDidSelect:(NSNotification *)notification {
    FontListController *flc = [notification object];
    UIPopoverController *popoverController = flc.container;
    [popoverController dismissPopoverAnimated:YES];
    [self handleDismissedPopoverController:popoverController];
    self.currentPopover = nil;
}     
     
     
#pragma mark Popover controller delegate

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    [self handleDismissedPopoverController:popoverController];
}





@end


/*
 
 UIViewController* vCtrl = [[UIViewController alloc] init];
 UIPopoverController* popController = [[UIPopoverController alloc] initWithContentViewController:vCtrl];
 
 popController.popoverContentSize = CGSizeMake(320,480);
 CGrect rect = CGRectMake(0,0,2,2);
 
 [popController presentPopoverFromRect:rect 
 inView:aView
 permittedArrowDirections:UIPopoverArrowDirectionUp
 animated:YES];
 
 
 在使用该控制器的时候，下面几个步骤是必须的：
 1.UIPopoverController该控制器的内容必须由一个控制器提供；提供方式有三：
 
 - (id)initWithContentViewController:(UIViewController *)viewController
 @property (nonatomic, retain) UIViewController *contentViewController
 - (void)setContentViewController:(UIViewController *)viewController animated:(BOOL)animated
 
 2.设置箭头方向：
 @property (nonatomic, readonly) UIPopoverArrowDirection popoverArrowDirection
 
 3.设置内容大小：
 @property (nonatomic) CGSize popoverContentSize
 
 备注：
 <1>.如果从一个导航按钮处呈现，使用：
 presentPopoverFromBarButtonItem:permittedArrowDirections:animated:；
 如果要从一个视图出呈现，使用：
 presentPopoverFromRect:inView:permittedArrowDirections:animated:
 
 <2>.如果设备旋转以后，位置定位错误需要在父视图控制器的下面方法里面重新定位：
 didRotateFromInterfaceOrientation:（在这个方法体里面重新设置rect）
 然后再次调用：
 - (void)presentPopoverFromRect:(CGRect)rect inView:(UIView *)view permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections animated:(BOOL)animated
 
 */
